package com.gluck.cases.common.utils.log;


import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * BaseLogInterceptor
 *
 * @author shiyongzhe
 * @date 10/21/21
 * @desc 日志拦截器抽象基类
 **/
public abstract class BaseLogInterceptor implements MethodInterceptor {


    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Method[] methods = Object.class.getMethods();
        // 过滤原生方法,防止底层toString 报错
        for (Method method : methods){
            if(invocation.getMethod().equals(method)){
                return null;
            }
        }
        return bussinessInvoke(invocation);
    }

    /**
     * 子拦截自行处理
     * @param invocation
     * @return
     */
    public abstract Object bussinessInvoke(MethodInvocation invocation)throws Throwable;

    /**
     * 构造请求方法(类名字 + 方法名字)
     * @param invocation
     * @return
     */
    protected String buildAccessName(MethodInvocation invocation){
        Method method = invocation.getMethod();
        String className = method.getDeclaringClass().getSimpleName();
        String methodName = method.getName();
        return className + "." + methodName;
    }

    /**
     * 构造请求文本
     * @param args
     * @return
     */
    protected String buildArguments(Object[] args){
        if(args.length == 0){
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder(128);
        Arrays.stream(args).forEach(x->{
            stringBuilder.append("[");
            stringBuilder.append(String.valueOf(x));
            stringBuilder.append("]");
        });
        return stringBuilder.toString();
    }
}
